package com.ly.honor.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.honor.entity.Honor;
import com.ly.honor.entity.Player;
import com.ly.honor.entity.dto.PlayerCreateDTO;
import com.ly.honor.entity.dto.PlayerEditDTO;
import com.ly.honor.entity.dto.PlayerQueryDTO;
import com.ly.honor.entity.vo.ClueQueryVO;
import com.ly.honor.entity.vo.PlayerQueryVO;
import com.ly.honor.entity.vo.PlayerSpreadVO;
import com.ly.honor.excel.PlayerExportVO;
import com.ly.honor.excel.PlayerImportDTO;
import com.ly.honor.exception.HonorException;
import com.ly.honor.listener.PlayerListener;
import com.ly.honor.mapper.HonorMapper;
import com.ly.honor.mapper.HonorPlayerMapper;
import com.ly.honor.service.PlayerService;
import com.ly.honor.mapper.PlayerMapper;
import com.ly.honor.util.HonorUtil;
import com.ly.honor.util.ResultEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author 17798
* @description 针对表【bs_player】的数据库操作Service实现
* @createDate 2022-11-16 11:49:49
*/
@Service
public class PlayerServiceImpl extends ServiceImpl<PlayerMapper, Player>
    implements PlayerService{

    @Autowired
    private PlayerMapper playerMapper;

    @Autowired
    private PlayerListener playerListener;

    @Autowired
    private HonorUtil honorUtil;

    @Autowired
    private HonorPlayerMapper honorPlayerMapper;

    @Autowired
    private HonorMapper honorMapper;


    @Override
    public Page<PlayerQueryVO> selectPlayerPage(long pageNum, long pageSize, PlayerQueryDTO playerQueryDTO) {
        Page<PlayerQueryVO> page = new Page<PlayerQueryVO>(pageNum,pageSize);
        Page<PlayerQueryVO> playerQueryVOPage = playerMapper.selectPlayerPage(page,playerQueryDTO);
        for (PlayerQueryVO c:playerQueryVOPage.getRecords()) {
            if(c.getPicture() != null){
                c.setPicture(c.getPicture().split("\\?")[0]);
            }
        }
        return playerQueryVOPage;
    }

    @Override
    public String upload(MultipartFile file) {
        var url = honorUtil.uploadFile(file);
        return url;
    }

    @Override
    public void deletePlayerById(long id) {
        //删除荣誉与选手相关表中的信息
        honorPlayerMapper.deletePlayerByPlayerId(id);
        //删除选手信息
        playerMapper.deleteById(id);
    }

    @Override
    public void removeBatch(List<Long> idList) {
        //删除荣誉与选手相关表中的信息
        honorPlayerMapper.removeBatchByPlayer(idList);

        playerMapper.deleteBatchIds(idList);
    }

    @Override
    public void insertPlayer(PlayerCreateDTO playerCreateDTO) {
        if(ObjectUtils.isEmpty(playerCreateDTO)){
            throw new HonorException(ResultEnum.OBJECT_NOT_NULL);
        }
        var checkPlayer = playerMapper.selectOne(new LambdaQueryWrapper<Player>().eq(Player::getName,playerCreateDTO.getName()));
        if(!ObjectUtils.isEmpty(checkPlayer)){
            throw new HonorException("该选手已存在");
        }
        var player = new Player();
        BeanUtils.copyProperties(playerCreateDTO,player);
        if(player.getPicture() != null && player.getPicture().length() != 0){
            player.setPicture(player.getPicture().split("\\?")[0]);
        }
        playerMapper.insert(player);
    }

    @Override
    public void updatePlayer(PlayerEditDTO playerEditDTO) {
        if(ObjectUtils.isEmpty(playerEditDTO)){
            throw new HonorException(ResultEnum.OBJECT_NOT_NULL);
        }
//        var checkPlayer = playerMapper.selectOne(new LambdaQueryWrapper<Player>().eq(Player::getName,playerEditDTO.getName()));
//        if(!ObjectUtils.isEmpty(checkPlayer)){
//            throw new HonorException("该选手已存在");
//        }
        var player = new Player();
        BeanUtils.copyProperties(playerEditDTO,player);
        if(player.getPicture() != null && player.getPicture().length() != 0){
            player.setPicture(player.getPicture().split("\\?")[0]);
        }
        playerMapper.updateById(player);
    }

    @Override
    public PlayerQueryVO getPlayerById(long id) {
        PlayerQueryVO playerQueryVO = playerMapper.getPlayerById(id);
        if(ObjectUtils.isEmpty(playerQueryVO)){
            throw new HonorException(ResultEnum.MESSAGE_INVALID);
        }
        return playerQueryVO;
    }

    @Override
    public void retirePlayer(List<Long> idList) {
        playerMapper.retirePlayer(idList);
    }

    @Override
    public void comebackPlayer(List<Long> idList) {
        playerMapper.comebackPlayer(idList);
    }

    @Override
    public void exportNowPlayerExcel(HttpServletResponse response) {
        try {
            String fileName = URLEncoder.encode("现役选手表","UTF-8");
            response.setHeader("Content-disposition","attachment;filename=" + fileName + ".xlsx");

            List<Player> playerList = playerMapper.selectList(null);
            playerList = playerList.stream().filter(player -> player.getRetireFlag() == 0).collect(Collectors.toList());
            List<PlayerExportVO> playerExportVOList = new ArrayList<PlayerExportVO>();
            playerList.forEach(player -> {
                var playerExportVO = new PlayerExportVO();
                BeanUtils.copyProperties(player,playerExportVO);
                playerExportVOList.add(playerExportVO);
            });
            EasyExcel.write(response.getOutputStream(), PlayerExportVO.class)
                    .sheet("现役选手表")
                    .doWrite(playerExportVOList);
        } catch (Exception e) {
            throw new HonorException("导出失败");
        }
    }

    @Override
    public void exportRetirePlayerExcel(HttpServletResponse response) {
        try {
            String fileName = URLEncoder.encode("退役选手表","UTF-8");
            response.setHeader("Content-disposition","attachment;filename=" + fileName + ".xlsx");

            List<Player> playerList = playerMapper.selectList(null);
            playerList = playerList.stream().filter(player -> player.getRetireFlag() == 1).collect(Collectors.toList());
            List<PlayerExportVO> playerExportVOList = new ArrayList<PlayerExportVO>();
            playerList.forEach(player -> {
                var playerExportVO = new PlayerExportVO();
                BeanUtils.copyProperties(player,playerExportVO);
                playerExportVOList.add(playerExportVO);
            });


            EasyExcel.write(response.getOutputStream(), PlayerExportVO.class)
                    .sheet("退役选手表")
                    .doWrite(playerExportVOList);
        } catch (Exception e) {
            throw new HonorException("导出失败");
        }
    }

    @Override
    public void importNowPlayerExcel(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), PlayerImportDTO.class,playerListener)
                    .sheet().doRead();
        } catch (IOException e) {
            throw new HonorException("导入失败");
        }
    }

    @Override
    public List<JSONObject> getPlayerSpread() {

        List<PlayerSpreadVO> playerSpreadVOList = playerMapper.getPlayerSpread();
        var playerSpreadList = new ArrayList<JSONObject>();
        playerSpreadVOList.forEach(playerSpreadVO -> {
            var jsonObject = new JSONObject();
            jsonObject.put("value",playerSpreadVO.getPlayerCount());
            jsonObject.put("name",playerSpreadVO.getCountryName());
            playerSpreadList.add(jsonObject);
        });
        return playerSpreadList;
    }

    @Override
    public List<PlayerQueryVO> getNowPlayerList() {
        List<PlayerQueryVO> playerList = playerMapper.getNowPlayerList();
        for (PlayerQueryVO playerQueryVO: playerList){
            var playerId = playerQueryVO.getId();
            List<Integer> honorIdList = honorPlayerMapper.getHonorIdrByPlayer(playerId);
            var honorList = new ArrayList<Honor>();
            for (Integer honorId : honorIdList){
                var honor = honorMapper.selectById(honorId);
                honorList.add(honor);
            }
            playerQueryVO.setHonorList(honorList);
        }
        return playerList;
    }

    @Override
    public List<PlayerQueryVO> getRetirePlayerList() {
        List<PlayerQueryVO> playerList = playerMapper.getRetirePlayerList();
        for (PlayerQueryVO playerQueryVO: playerList){
            var playerId = playerQueryVO.getId();
            List<Integer> honorIdList = honorPlayerMapper.getHonorIdrByPlayer(playerId);
            var honorList = new ArrayList<Honor>();
            for (Integer honorId : honorIdList){
                var honor = honorMapper.selectById(honorId);
                honorList.add(honor);
            }
            playerQueryVO.setHonorList(honorList);
        }
        return playerList;
    }

    @Override
    public List<PlayerQueryVO> getPlayerListByCondition(PlayerQueryDTO playerQueryDTO) {
        List<PlayerQueryVO> playerQueryVOList = playerMapper.getPlayerListByCondition(playerQueryDTO);
        for (PlayerQueryVO playerQueryVO: playerQueryVOList){
            var playerId = playerQueryVO.getId();
            List<Integer> honorIdList = honorPlayerMapper.getHonorIdrByPlayer(playerId);
            var honorList = new ArrayList<Honor>();
            for (Integer honorId : honorIdList){
                var honor = honorMapper.selectById(honorId);
                honorList.add(honor);
            }
            playerQueryVO.setHonorList(honorList);
        }
        return playerQueryVOList;
    }
}




